<template>
  <div>
    <!-- 面包屑区域 -->
    <Breadcrumb></Breadcrumb>
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="row">
        <el-col :span="24">
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="selectOptions1"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!--tab 动态 静态区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddParamsDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="attrHandleClose(tag)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="attrInputConfirm(scope.row)"
                  @blur="attrInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  @click="removeParamsDialog(scope.row.attr_id)">删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="showAddParamsDialog"
            >添加属性</el-button
          >
          <!-- 静态表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand"></el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete"
                   @click="removeParamsDialog(scope.row.attr_id)">删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsDialogVisible"
      @close="addDialogClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
      >
        <el-form-item
          :label="titleText"
          :label-width="'100px'"
          prop="attr_name"
        >
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Breadcrumb from "../Breadcrumb";
export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      // 所有商品分类数据
      cateList: [],
      selectOptions1: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择框双向绑定数组
      selectedCateKeys: [],
      // 被激活的Tab页签名称
      activeName: "many",
      //   动态参数表格数据
      manyTableData: [],
      //   静态数据表格数据
      onlyTableData: [],
      //   对话框的显示与隐藏
      addParamsDialogVisible: false,
      // 添加参数的表单数据对象
      addParamsForm: {
        attr_name: "", //参数名称	不能为空
        attr_sel: "", //	[only,many]	不能为空
        attr_vals: null, // 如果是 many 就需要填写值的选项，以逗号分隔
        attr_id: null, // 参数Id
      },
      // 添加表单的验证对象
      addParamsFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      addOrEditFlag: false, //false 添加    true 修改
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      let { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类数据失败！");
      this.cateList = res.data;
    },
    //   级联选择框变化触发函数
    handleChange() {
      this.getParamsData();
    },
    // 切换tab点击事件
    handleClick() {
      this.getParamsData();
    },
    // tab页签的点击函数
    async getParamsData() {
      //   证明选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.manyTableData = [];
        this.onlyTableData = [];
        this.selectedCateKeys = [];
        this.$message.error("只允许为三级分类设置参数！");
        return;
      }
      //   根据所选分类的ID和当前所处的面板，获取对应的参数
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((item, index) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
      //   console.log(res);
      //   console.log(this.selectedCateKeys);
    },
    // 添加按钮  事件
    showAddParamsDialog() {
      this.addParamsDialogVisible = true;
      this.addOrEditFlag = false;
    },
    // 对话框关闭事件
    addDialogClosed() {
      this.addParamsForm.attr_name = "";
      this.$refs.addParamsFormRef.resetFields();
    },
    // 添加或修改 点击确定事件
    addParams() {
      this.$refs.addParamsFormRef.validate(async (valid) => {
        if (!valid) return;
        this.addParamsForm.attr_sel = this.activeName;
        if (this.addOrEditFlag) {
          // 为true的时候是修改
          var { data: res } = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.addParamsForm.attr_id}`,
            this.addParamsForm
          );
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        } else {
          var { data: res } = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            this.addParamsForm
          );
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        }
        await this.getParamsData();
        this.$message.success(res.meta.msg);
        this.addParamsDialogVisible = false;
      });
    },
    // 修改参数 回填
    editParamsDialog(row) {
      //   console.log("修改参数源数据", row);
      this.addOrEditFlag = true;
      this.addParamsForm.attr_name = row.attr_name;
      this.addParamsForm.attr_id = row.attr_id;
      this.addParamsDialogVisible = true;
    },
    //展示参数输入框
    showInput(data) {
      data.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    //回车键抬起或者鼠标失去焦点回调
    async attrInputConfirm(data) {
      data.inputVisible = false;
      if (!data.inputValue) {
        return;
      } else {
        if (data.attr_vals.includes(data.inputValue)) {
          return this.$message.error("该属性已存在");
        }
        data.attr_vals.push(data.inputValue);
        let sendData = {
          attr_name: data.attr_name,
          attr_sel: data.attr_sel,
          attr_vals: data.attr_vals.join(","),
        };
        let { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${data.attr_id}`,
          sendData
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
      }
      data.inputValue = "";
    },
    // 删除事件
    async removeParamsDialog(attrId){
        let config = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) =>err );
        console.log(config);
        if(config !=='confirm') return this.$message.info('已取消删除')
        let { data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if(res.meta.status !==200) return this.$message.error(res.meta.msg)
         this.$message.success(res.meta.msg)
         this.getParamsData();
    }
  },
  computed: {
    // 计算数组的长度，来确定按钮是否禁用
    isDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // cateId
    cateId() {
      if (this.selectedCateKeys.length == 3) {
        return this.selectedCateKeys[2];
      }
    },
    titleText() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    },
  },
};
</script>
<style lang="scss" scoped>
.row,
.el-table {
  margin: 15px 0px;
}
.el-tag {
  margin: 5px;
  user-select: none;
}
.input-new-tag {
  margin: 0 5px;
  width: 150px;
}
.button-new-tag {
  margin-left: 5px;
}
</style>